package com.easy.dfc.web;

import com.alibaba.fastjson.JSONObject;
import com.easy.core.web.BaseController;
import com.easy.dfc.Utils.Error;
import com.easy.dfc.Utils.JsonUtil;
import com.easy.dfc.Utils.PagingUtil;
import com.easy.dfc.Utils.Util;
import com.easy.dfc.entity.*;
import com.easy.dfc.service.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by VULCANTSeries on 2017/5/17.
 */
@Controller
@RequestMapping("${apiPath}/factory")
public class FactorySetController extends BaseController {

    @Resource
    private FactorySetService factorySetService;

    @Resource
    private ProductsetService productsetService;

    @Resource
    private UsersetService usersetService;

    @Resource
    private TiantiantejiaService tiantiantejiaService;

    @Resource
    private TiaoweihuosetService tiaoweihuosetService;

    @Resource
    private TuangouService tuangouService;

    @Resource
    private BrandSetService brandSetService;

    @Resource
    private TagGroupSetService tagGroupSetService;

    /**
     * * 店铺列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/FactoryList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> FactoryList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int start = Integer.parseInt(request.getParameter("Page"));
            int type = Integer.parseInt(request.getParameter("Type"));
            PagingUtil pagingUtil = new PagingUtil();
            pagingUtil.setStart((start - 1) * 20);
            pagingUtil.setBrandId(type);
            List<FactorySetWithBLOBs> factorySetWithBLOBses = factorySetService.selectBy20(pagingUtil);
            //遍历每个店铺，获取每个店铺的产品列表
            for (FactorySetWithBLOBs f : factorySetWithBLOBses) {
                List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectByFactoryId(f.getId());
                //遍历每条数据，判断是否在活动中
                for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                    Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
                }
                f.setProductsetWithBLOBsList(productsetWithBLOBsList);
            }
            String str = JSONObject.toJSONString(factorySetWithBLOBses);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 店铺产品列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/FactoryProductList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> FactoryProductList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int factoryId = Integer.parseInt(request.getParameter("FactoryId"));
            int start = Integer.parseInt(request.getParameter("Page"));
            PagingUtil pagingUtil = new PagingUtil();
            pagingUtil.setStart((start - 1) * 20);
            pagingUtil.setBrandId(factoryId);
            List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectByFactoryIdFor20(pagingUtil);
            //遍历每条数据，判断是否在活动中
            for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
            }
            String str = JSONObject.toJSONString(productsetWithBLOBsList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 店铺上新产品列表,取出该店铺3天内发布的产品
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/FactoryNewProductList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> FactoryNewProductList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int factoryId = Integer.parseInt(request.getParameter("FactoryId"));
            int start = Integer.parseInt(request.getParameter("Page"));
            PagingUtil pagingUtil = new PagingUtil();
            pagingUtil.setStart((start - 1) * 20);
            pagingUtil.setBrandId(factoryId);
            Date date = new Date(new Date().getTime() - 3 * 24 * 60 * 60 * 1000);
            pagingUtil.setDate(date);
            List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectByFactoryIdForNew(pagingUtil);
            //遍历每条数据，判断是否在活动中
            for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
            }
            String str = JSONObject.toJSONString(productsetWithBLOBsList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 店铺首页产品列表，按品牌分类
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/HomeBrandProductList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> HomeBrandProductList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int factoryId = Integer.parseInt(request.getParameter("FactoryId"));
            List<BrandSet> brandSetList = brandSetService.selectByFactory(factoryId);
            //遍历每个品牌，获取每个品牌的产品列表
            for (BrandSet b : brandSetList) {
                List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectByBrandId(b.getId());
                //遍历每条数据，判断是否在活动中
                for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                    Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
                }
                b.setProductsetWithBLOBsList(productsetWithBLOBsList);
            }
            String str = JSONObject.toJSONString(brandSetList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 根据传入的品牌Id返回的该品牌产品列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/BrandProductList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> BrandProductList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int BrandId = Integer.parseInt(request.getParameter("BrandId"));
            int start = Integer.parseInt(request.getParameter("Page"));
            PagingUtil pagingUtil = new PagingUtil();
            pagingUtil.setStart((start - 1) * 20);
            pagingUtil.setBrandId(BrandId);
            List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectByBrandIdList(pagingUtil);
            //遍历每条数据，判断是否在活动中
            for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
            }
            String str = JSONObject.toJSONString(productsetWithBLOBsList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 店铺首页产品列表，按类目分类
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/HomeTagProductList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> HomeTagProductList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int factoryId = Integer.parseInt(request.getParameter("FactoryId"));
            List<TagSet> tagSets = tagGroupSetService.selectTagAll();
            List<TagGroupSet> tagGroupSets = new ArrayList<>();
            //遍历每个一级类目，获取每个类目的产品列表
            for (TagSet t : tagSets) {
                List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectByTagId(t.getId(), factoryId);
                //如果该类目没有产品，则从集合中删除该类目
                if (productsetWithBLOBsList == null || productsetWithBLOBsList.size() == 0) {
                    tagSets.add(t);
                    continue;
                }
                //遍历每条数据，判断是否在活动中
                for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                    Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
                }
                t.setProductsetWithBLOBsList(productsetWithBLOBsList);
            }
            //将没有产品的类目删除不返回
            tagSets.removeAll(tagGroupSets);
            String str = JSONObject.toJSONString(tagSets);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * * 根据传入的标签Id返回的该类目产品列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/TagProductList", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> TagProductList(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
//            String userId = request.getParameter("UserId");
//            String token = request.getParameter("Token");
//            if (!usersetService.VerifyToken(userId, token)) {
//                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
//                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
//            }
            int BrandId = Integer.parseInt(request.getParameter("TagId"));
            int start = Integer.parseInt(request.getParameter("Page"));
            PagingUtil pagingUtil = new PagingUtil();
            pagingUtil.setStart((start - 1) * 20);
            pagingUtil.setBrandId(BrandId);
            List<ProductsetWithBLOBs> productsetWithBLOBsList = productsetService.selectByTagIdList(pagingUtil);
            //遍历每条数据，判断是否在活动中
            for (ProductsetWithBLOBs p : productsetWithBLOBsList) {
                Util.PromotionStuts(p, tiantiantejiaService, tiaoweihuosetService, tuangouService);
            }
            String str = JSONObject.toJSONString(productsetWithBLOBsList);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 获取店铺信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getFactoryInfo", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> getFactoryInfo(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
            int FactoryId = Integer.parseInt(request.getParameter("FactoryId"));
            FactorySetWithBLOBs factorySetWithBLOBs = factorySetService.selectByFactoryId(FactoryId);
            String str = JSONObject.toJSONString(factorySetWithBLOBs);
            jsonObject = JSONObject.parseObject(JsonUtil.toErrJson(Error.OK, str));
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 更改店铺分类
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateFactoryType", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> updateFactoryType(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpSession session = request.getSession();
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", com.easy.dfc.Utils.Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            int FactoryId = Integer.parseInt(request.getParameter("FactoryId"));
            int Type = Integer.parseInt(request.getParameter("Type"));
            FactorySetWithBLOBs factorySetWithBLOBs = factorySetService.selectByFactoryId(FactoryId);
            factorySetWithBLOBs.setType(Type);
            factorySetService.updateByPrimaryKeySelective(factorySetWithBLOBs);
            jsonObject.put("Err", Error.OK);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }

    /**
     * 上传店招
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/Upload", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> Upload(HttpServletRequest request) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = request.getParameter("UserId");
            String token = request.getParameter("Token");
            if (!usersetService.VerifyToken(userId, token)) {
                jsonObject.put("Err", Error.ValidFailed);
                return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
            }
            int FactoryId = Integer.parseInt(request.getParameter("FactoryId"));
            FactorySetWithBLOBs factorySetWithBLOBs = factorySetService.selectByFactoryId(FactoryId);
            //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            //检查form中是否有enctype="multipart/form-data"
            if (multipartResolver.isMultipart(request)) {
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //获取multiRequest 中所有的文件名
                Iterator iter = multiRequest.getFileNames();

                while (iter.hasNext()) {
                    //一次遍历所有文件
                    MultipartFile file = multiRequest.getFile(iter.next().toString());
                    if (file != null) {
                        String key = new Date().getTime() + file.getOriginalFilename();
                        Util.OSSUpload("factoryimgs", key, file.getInputStream());
                        String path = "http://factoryimgs.oss-cn-shanghai.aliyuncs.com/" + key;
                        factorySetWithBLOBs.setStoreImg(path);
                        factorySetService.updateByPrimaryKeySelective(factorySetWithBLOBs);
                        jsonObject.put("Err", Error.OK);
                    }
                }
            }
        } catch (IOException e) {
            jsonObject.put("Err", Error.UploadFaild);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        } catch (Exception e) {
            jsonObject.put("Err", Error.OtherError);
            return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
        }
        return new ResponseEntity<JSONObject>(jsonObject, responseHeaders, HttpStatus.OK);
    }
}
